<template>
  <div class="mod-demo-echarts">
    <el-form :inline="true" @keyup.enter.native="reFetchData()">
      <el-form-item>
        <!-- 时间 -->
        <el-date-picker
          v-model="startAndEndTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '00:00:00']"
        >
          >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button @click="reFetchData()">展示</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div id="J_chartLineBox" class="chart-box"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <div id="J_chartPieBox" class="chart-box"></div>
        </el-card>
      </el-col>

      <!-- <el-col :span="24">
        <el-card>
          <div id="J_chartBarBox" class="chart-box"></div>
        </el-card>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
import echarts from 'echarts'
export default {
  computed: {
    startTime: {
      get () {
        if (this.startAndEndTime) {
          return this.startAndEndTime[0]
        } else {
          return ''
        }
      }
    },
    endTime: {
      get () {
        if (this.startAndEndTime) {
          return this.startAndEndTime[1]
        } else {
          return ''
        }
      }
    }
  },
  data () {
    return {
      startAndEndTime: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      saleCountPieDataList: [],
      lineData: [],
      lineTimeUnit: 'month',
      lineChar: {
        xAxisData: [],
        seriesFirst: [],
        seriesSecond: []
      },
      chartLine: null,
      chartBar: null,
      chartPie: null,
      chartScatter: null
    }
  },
  mounted () {
    this.reFetchData()
  },
  activated () {
    // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
    if (this.chartLine) {
      this.chartLine.resize()
    }
    if (this.chartBar) {
      this.chartBar.resize()
    }
    if (this.chartPie) {
      this.chartPie.resize()
    }
  },
  methods: {
    //  生成 本月 1日至 今日的 date，2020-11
    genCurrentMonthList () {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1

      let monthList = []
      for (let start = 1; start <= month; start++) {
        monthList.push(`${year}-${start}`)
      }
      return monthList
    },

    // 生成 本月 1日至 今日的 date
    genCurrentMonthDayListUntilToday () {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const dayOfMonth = now.getDate()

      let dayList = []
      for (let start = 1; start <= dayOfMonth; start++) {
        dayList.push(`${year}-${month}-${start}`)
      }

      return dayList
    },
    // 组装折线图数据
    prepareLineData () {
      let that = this
      let lineDataMap = {}
      let lineDataDateList = that.lineData.map((item) => {
        lineDataMap[item.date] = item
        return item.date
      })

      if (this.lineTimeUnit === 'day') {
      // 本月内的 日期
        const currentMonthUntilTodayDayList = this.genCurrentMonthDayListUntilToday()
      // debugger
      // 比对后端数据中，是否存在 day日期，如果不存在，则为0
        for (const day of currentMonthUntilTodayDayList) {
          that.lineChar.xAxisData.push(day)
        // 存在
          if (lineDataDateList.indexOf(day) > -1) {
            const currentDayData = lineDataMap[day]
          // debugger
            that.lineChar.seriesFirst.push(currentDayData.orderCount)
            that.lineChar.seriesSecond.push(currentDayData.turnoverCount)
          } else {
            that.lineChar.seriesFirst.push(0)
            that.lineChar.seriesSecond.push(0)
          }
        }
      } else if (this.lineTimeUnit === 'month') {
          // 本年的月份
        const monthList = this.genCurrentMonthList()

          // 比对后端数据中，是否存在 day日期，如果不存在，则为0
        for (const month of monthList) {
          that.lineChar.xAxisData.push(month)
        // 存在
          if (lineDataDateList.indexOf(month) > -1) {
            const currentDayData = lineDataMap[month]
          // debugger
            that.lineChar.seriesFirst.push(currentDayData.orderCount)
            that.lineChar.seriesSecond.push(currentDayData.turnoverCount)
          } else {
            that.lineChar.seriesFirst.push(0)
            that.lineChar.seriesSecond.push(0)
          }
        }
      }
    },
    reFetchData () {
      this.getSaleCountPieData()
      this.getLineData()
    },
    // 获取 折线图 数据
    getLineData () {
      // 重置
      this.lineData = []
      this.lineChar = {
        xAxisData: [],
        seriesFirst: [],
        seriesSecond: []
      }

      this.dataListLoading = true

      this.$http({
        url: this.$http.adornUrl(`/sys/chart/line/union/${this.lineTimeUnit}`),
        method: 'get',
        params: this.$http.adornParams({
          'startTime': this.startTime,
          'endTime': this.endTime
        })
      }).then(({ data }) => {
        console.log('折线图请求数据', data)
        if (data && data.code === 0) {
          this.lineData = data.data.orderCountVoList

          // 组装数据
          this.prepareLineData()
          // 初始化 Line 图
          this.initChartLine()
        } else {
          this.$message.error('折线图数据加载异常')
          this.lineData = []
        }
        this.dataListLoading = false
      })
    },
    // 获取 销量 pie 数据
    getSaleCountPieData () {
      // 重置
      this.saleCountPieDataList = []
      this.dataListLoading = true

      this.$http({
        url: this.$http.adornUrl('/sys/chart/pie/salecount'),
        method: 'get',
        params: this.$http.adornParams({
          'startTime': this.startTime,
          'endTime': this.endTime
        })
      }).then(({ data }) => {
        console.log('请求数据', data)
        if (data && data.code === 0) {
          this.saleCountPieDataList = data.data

          // 初始化pie 图
          this.initChartPie()
        } else {
          this.$message.error('数据加载异常')
          this.saleCountPieDataList = []
        }
        this.dataListLoading = false
      })
    },
    // 折线图
    initChartLine () {
      let that = this
      var option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['成交订单数', '销售额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            // saveAsImage: {},
            dataView: {},
            magicType: {
              type: ['line', 'bar']
            },
            // myToolYear: {
            //   show: true,
            //   title: '按年',
            //   icon: 'image://http://cdn.350800.xyz/20201124/ba79299281024fd590e8816180aa89b8.jpg',
            //   onclick: function () {
            //     alert('myToolHandler2')
            //   }
            // },
            myToolMonth: {
              show: true,
              title: '按月',
              icon: 'image://http://cdn.350800.xyz/20201124/4158efd2d24f4542996f436fb793e4c8.jpg',
              onclick: function () {
                that.lineTimeUnit = 'month'
                that.getLineData()
                that.chartLine.resize()
              }
            },
            myToolDay: {
              show: true,
              title: '按月',
              icon: 'image://http://cdn.350800.xyz/20201124/b8634dac02e54498a64674d0d57681b0.jpg',
              onclick: function () {
                that.lineTimeUnit = 'day'
                that.getLineData()
                that.chartLine.resize()
              }
            }

          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: that.lineChar.xAxisData
        },
        yAxis: {
          type: 'log'
        },
        series: [
          {
            name: '成交订单数',
            type: 'line',
            stack: '成交订单数',
            data: that.lineChar.seriesFirst
          },
          {
            name: '销售额',
            type: 'line',
            stack: '销售额',
            data: that.lineChar.seriesSecond
          }
        ]
      }
      this.chartLine = echarts.init(document.getElementById('J_chartLineBox'))
      this.chartLine.setOption(option)
      window.addEventListener('resize', () => {
        this.chartLine.resize()
      })
    },

    // 饼状图
    initChartPie () {
      let that = this
      console.log('饼状图数据', that.saleCountPieDataList)

      var option = {
        backgroundColor: '#2c343c',
        title: {
          text: '历史销量',
          left: 'center',
          top: 20,
          textStyle: {
            color: '#ccc'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        visualMap: {
          show: false,
          min: 80,
          max: 600,
          inRange: {
            colorLightness: [0, 1]
          }
        },
        series: [
          {
            name: '商品类别',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: that.saleCountPieDataList.sort(function (a, b) {
              return a.value - b.value
            }),

            roseType: 'radius',
            label: {
              normal: {
                textStyle: {
                  color: 'rgba(255, 255, 255, 0.3)'
                }
              }
            },
            labelLine: {
              normal: {
                lineStyle: {
                  color: 'rgba(255, 255, 255, 0.3)'
                },
                smooth: 0.5,
                length: 10,
                length2: 20
              }
            },

            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return Math.random() * 50
            }
          }
        ]
      }
      this.chartPie = echarts.init(document.getElementById('J_chartPieBox'))
      this.chartPie.setOption(option)
      window.addEventListener('resize', () => {
        this.chartPie.resize()
      })
    }
  }
}
</script>

<style lang="scss">
.mod-demo-echarts {
  > .el-alert {
    margin-bottom: 10px;
  }
  > .el-row {
    margin-top: -10px;
    margin-bottom: -10px;
    .el-col {
      padding-top: 10px;
      padding-bottom: 10px;
    }
  }
  .chart-box {
    min-height: 400px;
  }
}
</style>
